package com.xqboss.apps.service.consumer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.domain.consumer.ConsumerContacts;
import com.xqboss.apps.dto.consumer.ContactsUploadDto;
import com.xqboss.apps.mapper.consumer.ConsumerContactsMapper;
import com.xqboss.apps.vo.consumer.ConsumerContactsVo;
import com.xqboss.common.core.domain.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 好友通讯录表接口
 *
 * @author wangcong
 * @date 2023-08-28
 */
@Service
public class ConsumerContactsService extends ServiceImpl<ConsumerContactsMapper, ConsumerContacts> {

    @Resource
    private ConsumerContactsMapper consumerContactsMapper;

    public R contactsUpload(ContactsUploadDto dto) {
        if (ObjUtil.isNull(dto) || CollUtil.isEmpty(dto.getContactsList())) {
            return R.fail("参数错误");
        }
        LambdaQueryWrapper<ConsumerContacts> wq = new LambdaQueryWrapper<>();
        wq.eq(ConsumerContacts::getUserId, dto.getUserId());
        List<ConsumerContacts> list = this.list(wq);

        List<ConsumerContacts> data2 = dto.getContactsList();
        data2.removeIf(num -> !Validator.isMobile(num.getUserName()));
        if (CollUtil.isEmpty(list)) {
            data2.forEach(item -> {item.setUserId(dto.getUserId());});
            saveBatch(data2);
            return R.ok();
        }

        //去除相同元素
        List<ConsumerContacts> collect = data2.stream()
                .filter(d1 ->
                        list.stream()
                                .noneMatch(d2 -> StrUtil.equals(d1.getUserName(), d2.getUserName()))
                ).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            collect.forEach(item -> {item.setUserId(dto.getUserId());});
            saveBatch(collect);
        }
        return R.ok();
    }

    public List<ConsumerContactsVo> contactsList(Long userId) {
        return consumerContactsMapper.contactsList(userId);
    }
}
